package com.xuecheng.content.service.jobhandler;

import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.content.service.CoursePublishService;
import com.xuecheng.messagesdk.model.po.MqMessage;
import com.xuecheng.messagesdk.service.MessageProcessAbstract;
import com.xuecheng.messagesdk.service.MqMessageService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;

@Slf4j
@Component
public class CoursePublishTask extends MessageProcessAbstract {
        @Autowired
        CoursePublishService coursePublishService;
    //课程发布消息类型
    public static final String MESSAGE_TYPE = "course_publish";
    @XxlJob("CoursePublishJobHandler")
    public void coursePublishJobHandler() throws Exception {
        // 分片参数
        int shardIndex = XxlJobHelper.getShardIndex();
        int shardTotal = XxlJobHelper.getShardTotal();
        log.debug("shardIndex="+shardIndex+",shardTotal="+shardTotal);
        //参数:分片序号、分片总数、消息类型、一次最多取到的任务数量、一次任务调度执行的超时时间
        process(shardIndex,shardTotal,MESSAGE_TYPE,5,60);
    }
    @Override
    public boolean execute(MqMessage mqMessage) {
//        将课程信息进行静态化   将静态页面上传到minio中
        generateCourseHtml(mqMessage,Long.valueOf(mqMessage.getBusinessKey1()));
//        课程缓存
//        课程索引
        saveCourseIndex(mqMessage,Long.valueOf(mqMessage.getBusinessKey1()));
        return true;
    }

    private void generateCourseHtml(MqMessage mqMessage, Long courseId) {
//        消息id
        Long id = mqMessage.getId();
        MqMessageService mqMessageService = this.getMqMessageService();
//        判断任务是否完成
        int stageOne = mqMessageService.getStageOne(id);
        if (stageOne>0) {
            log.debug("当前阶段是静态化课程信息任务已经完成不在处理，任务信息:{}",mqMessage);
            return;
        }
//        生成静态文件
        File file = coursePublishService.generateCourseHtml(courseId);
        if (file==null) {
            XueChengPlusException.cast("课程静态化异常");
        }
//        将html文件上传至minIo
        coursePublishService.uploadCourseHtml(courseId,file);
//        保存第一阶段状态
        mqMessageService.completedStageOne(id);

    }

//  课程静态化查询
    private void saveCourseIndex(MqMessage mqMessage, Long courseId) {
//        消息id
        Long id = mqMessage.getId();
        MqMessageService mqMessageService = this.getMqMessageService();
//        判断任务是否完成
        int stageTwo = mqMessageService.getStageTwo(id);  //第二阶段  索引 查询 es
        if (stageTwo>0) {
            log.debug("当前阶段是静态化课程信息任务已经完成不在处理，任务信息:{}",mqMessage);
            return;
        }
//
        Boolean aBoolean = coursePublishService.saveCourseIndex(courseId);
//        保存第二阶段状态
        mqMessageService.completedStageTwo(id);

    }
}
